package cn.itsource.org.service.Impl;

import cn.itsource.basic.service.Impl.BaseSerivcelmpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.DepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseSerivcelmpl<Department,DepartmentQuery> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void save(Department department) {
        departmentMapper.insertSelective(department);
        long[] parentIds = department.getParentIds();

        if (parentIds != null && parentIds.length>0) {
            //设置上级id
            department.setParentId(parentIds[parentIds.length-1]);
            StringBuffer stringBuffer = new StringBuffer("");
            for (long parentId : parentIds) {
                stringBuffer.append("/").append(parentId);
            }
              stringBuffer.append("/").append(department.getId());
              department.setDirPath(stringBuffer.toString());
        }else {
            department.setDirPath("/"+department.getId());
        }

        departmentMapper.updateByPrimaryKeySelective(department);
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKeySelective(department);
        this.save(department);
    }



    @Override
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Department> findAll() {

        return departmentMapper.selectAll();
    }

    @Override
    public Department findOne(Long id) {
        return departmentMapper.selectOneByExample(id);
    }

    @Override
    public PageList<Department> findPage(DepartmentQuery query) {
        //分页插件!!!!
        PageHelper.startPage(query.getPage(),query.getSize());
        List<Department> page = departmentMapper.findPage(query);
        //封装到pageInfo
        PageInfo<Department> info = new PageInfo<>(page);
        //封装自定义对象
        PageList<Department> pageList = new PageList<>(info.getTotal(), info.getList());
        return pageList;
    }

    @Override
    public void move(DepartmentQuery query) {
        if (query.getIds()==null || query.getIds().length==0 ){
            return;
        }
        departmentMapper.move(query.getIds());
    }

    @Override
    public List<Department> deptTree() {
        //查询所有部门数据,为递归准备
        List<Department> departments = departmentMapper.deptTree();
        //使用递归工具类
        List<Department> tree = TreeUtil.getTree(departments);
        return tree;
    }
}
